package com.demo.security.service.impl;

import com.demo.ex.ServiceException;
import com.demo.security.model.SysUser;
import com.demo.security.model.UserStatus;
import com.demo.security.service.JwtUserService;
import com.demo.security.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class JwtUserServiceImpl implements JwtUserService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser sysUser = userService.getUserByName(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名错误");
        }
        if (StringUtils.isEmpty(sysUser))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }
        else if (UserStatus.DELETED.getValue().equals(sysUser.getDeleted()))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        else if (UserStatus.DISABLE.getValue().equals(sysUser.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        // 用户可以访问的资源名称（或者说用户所拥有的权限） 注意：必须"ROLE_"开头
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_" + sysUser.getRole()));
        // 匹配用户密码
        return new org.springframework.security.core.userdetails.User(username, sysUser.getPassword(), authorities);
    }

    //    public UserDetails createLoginUser(SysUser user)
//    {
//        // 这里把user相关的权限信息也装载进来了，security并不需要这些信息，但我们之后的逻辑需求时，可以从security中把这些信息取出来，不需要再从数据库拿了，更方便
//        return new LoginUser(user, permissionService.getMenuPermission(user));
//    }
}
